package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckillController")
public class SeckillController {
    @DubboReference
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("seckillIndex")
    public String seckillIndex(Model model){
        List<TbSeckillGoods> SeckillGoodsList = seckillService.findSeckillList();
        model.addAttribute("SeckillGoodsList",SeckillGoodsList);
        return "seckill-index";
    }

    @RequestMapping("detail")
    public String detail(Long id,Model model){
        TbSeckillGoods goods = seckillService.selectById(id);
        model.addAttribute("goods",goods);
        return "seckill-item";
    }

    //创建订单
    @RequestMapping("creatOrder")
    @ResponseBody
    public Result creatOrder(Long id){
        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return Result.response(ResultEnum.NOLOGIN);
        }
        try {
            String usernameId = user.getUsername() + id;
            String uid = (String) redisTemplate.boundHashOps("seckill-username-goodId").get(usernameId);
            if (uid != null && uid.equals("1")){
                return Result.response(ResultEnum.PURCHASE);
            }

            seckillService.createOrder(id,user.getUsername());

        } catch (Exception e) {
            e.printStackTrace();
            return Result.response(ResultEnum.SALEOVER);
        }
        return Result.ok();
    }

    //创建订单
    @RequestMapping("getOrderId")
    @ResponseBody
    public Result getOrderId(){
        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        Long OrderId = seckillService.getOrderId(user.getUsername());
        if (OrderId == null){
            return Result.response(ResultEnum.ERROR);
        }
        return Result.ok().setData(OrderId);
    }
}
